import { Request, Response, NextFunction } from 'express';
import { verifyToken, JwtPayload } from '@/utils/jwt';
import { logger } from '@/utils/logger';
import { prisma } from '@/config/database';

// 扩展Request接口以包含用户信息
export interface AuthenticatedRequest extends Request {
  user?: {
    id: string;
    username: string;
  };
}

// JWT认证中间件
export const authenticateToken = async (
  req: AuthenticatedRequest,
  res: Response,
  next: NextFunction
): Promise<void> => {
  try {
    const authHeader = req.headers.authorization;
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
      res.status(401).json({
        success: false,
        message: '访问令牌缺失',
      });
      return;
    }

    const decoded = verifyToken(token) as JwtPayload;
    
    // 验证用户是否存在
    const user = await prisma.user.findUnique({
      where: { id: decoded.userId },
      select: {
        id: true,
        username: true,
      },
    });

    if (!user) {
      res.status(401).json({
        success: false,
        message: '用户不存在',
      });
      return;
    }

    req.user = {
      id: user.id,
      username: user.username,
    };

    next();
  } catch (error) {
    logger.error('Token verification failed:', error);
    res.status(401).json({
      success: false,
      message: '无效的访问令牌',
    });
  }
};

// 可选认证中间件（不强制要求认证）
export const optionalAuth = async (
  req: AuthenticatedRequest,
  res: Response,
  next: NextFunction
): Promise<void> => {
  try {
    const authHeader = req.headers.authorization;
    const token = authHeader && authHeader.split(' ')[1];

    if (token) {
      try {
        const decoded = verifyToken(token) as JwtPayload;
        
        // 验证用户是否存在
        const user = await prisma.user.findUnique({
          where: { id: decoded.userId },
          select: {
            id: true,
            username: true,
          },
        });

        if (user) {
          req.user = {
            id: user.id,
            username: user.username,
          };
        }
      } catch (error) {
        // 忽略token验证错误，继续处理请求
        logger.warn('Optional token verification failed:', error);
      }
    }

    next();
  } catch (error) {
    // 可选认证失败时不阻止请求继续
    logger.warn('Optional authentication failed:', error);
    next();
  }
};